package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.SysCfgCodeEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.vo.RoleVo;
import com.weixing.mall.provider.api.model.vo.SysConfigVo;
import com.weixing.mall.provider.api.service.SysConfigServiceFeign;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.mapper.AgentRenewMapper;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.model.domain.AgentLog;
import com.weixing.mall.provider.model.domain.AgentRenew;
import com.weixing.mall.provider.model.dto.renew.AgentRenewDto;
import com.weixing.mall.provider.model.dto.renew.AgentRenewEditDto;
import com.weixing.mall.provider.model.enums.AgentLogTypeEnum;
import com.weixing.mall.provider.model.query.AgencyFeeQuery;
import com.weixing.mall.provider.model.query.AgencyRecordQuery;
import com.weixing.mall.provider.model.vo.AgencyFeeVo;
import com.weixing.mall.provider.model.vo.AgentRenewVo;
import com.weixing.mall.provider.model.vo.renew.RenewStats;
import com.weixing.mall.provider.service.IAgentLogService;
import com.weixing.mall.provider.service.IAgentRenewService;
import com.weixing.mall.provider.service.IAgentService;
import com.weixing.mall.util.CommUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 代理商模块-代理商续费表 服务实现类
 *
 * @author Small
 * @since 2019-11-18
 */
@Service
public class AgentRenewServiceImpl extends ServiceImpl<AgentRenewMapper, AgentRenew> implements IAgentRenewService {

    @Autowired
    private IAgentService agentService;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private IAgentLogService agentLogService;
    @Autowired
    private SysConfigServiceFeign sysConfigServiceFeign;

    @Override
    public IPage<AgencyFeeVo> selectAgencyFeeListOfPage(Page page, AgencyFeeQuery agentRenewQuery, SysAuth auth) {
        Long uid = auth.getUid();
        List<RoleVo> list = sysUserRpcService.getRoleById(uid).getData();
        for (RoleVo vo : list) {
            if (vo.getRoleCode().equals(GlobalConstant.RoleCode.ADMIN)) {
                return baseMapper.selectAgencyFeeListOfPage(page, agentRenewQuery);
            }
        }
        for (RoleVo vo : list) {
            if (vo.getRoleCode().equals(GlobalConstant.RoleCode.KFADMIN)) {
                return baseMapper.selectAgencyFeeListOfPage(page, agentRenewQuery);
            }
        }
        agentRenewQuery.setCustomerId(uid);
        return baseMapper.selectAgencyFeeListOfPage(page, agentRenewQuery);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(AgentRenewDto agentRenewDto, SysAuth auth) {
        QueryWrapper<AgentRenew> wrapper = new QueryWrapper<AgentRenew>();
        wrapper.eq("agent_id", agentRenewDto.getAgentId());
        List<AgentRenew> list = list(wrapper);

        AgentRenew agentRenew = new AgentRenew();
        BeanUtils.copyProperties(agentRenewDto, agentRenew);
        agentRenew.setPayType(agentRenewDto.getPayType().getValue());
        agentRenew.setPayChannel(agentRenewDto.getPayChannel().getValue());
        DateTime startTime = DateUtil.parse(agentRenewDto.getEffectStart(), DatePattern.NORM_DATETIME_PATTERN);
        agentRenew.setEffectStart(startTime);
        DateTime effectEnd = DateUtil.parse(agentRenewDto.getEffectEnd(), DatePattern.NORM_DATETIME_PATTERN);
        int compare = DateUtil.compare(startTime, effectEnd);
        if (compare > 0){
            throw  new BusinessException("失效时间必须比生效时间晚");
        }
        agentRenew.setEffectEnd(effectEnd);
        Agent agent = agentService.getById(agentRenewDto.getAgentId());
        agentRenew.setAgentLevel(agent.getAgentLevel().intValue());
        if (null == agentRenewDto.getId()) {
            if (agentRenewDto.getAgentId() != null) {
                agentRenew.setCreatedBy(auth.getUid());
                agentRenew.setCreator(auth.getRealName());
                agentRenew.setCreatedTime(new Date());
                baseMapper.insert(agentRenew);
            }
        } else {
            baseMapper.updateById(agentRenew);
        }
        // 更改代理商表到期时间
        agent.setLastMaturityTime(agent.getMaturityTime());
        agent.setMaturityTime(effectEnd);
        if (CollUtil.isEmpty(list)) {
            agent.setFirstRenewTime(agentRenew.getCreatedTime());
        }

        createLog(auth, agentRenew, agent, list);

        agent.setIsEnable(WhetherEnum.YES.getValue());
        agent.setIsOfficial(WhetherEnum.YES.getValue());
        agentService.updateById(agent);
        return agentRenew.getId();
    }


    private void sendExpireQueue(Agent agent){
        Result<SysConfigVo> result = sysConfigServiceFeign.getByCode(SysCfgCodeEnum.AGENT_EXPIRE_ALERT.getCode());
        if (result.isSuccess()){
            SysConfigVo data = result.getData();
            Integer value = data.getCfgValue();
        }
    }

    private void createLog(SysAuth auth, AgentRenew agentRenew, Agent agent, List<AgentRenew> list) {
        AgentLog log = new AgentLog();
        log.setAgentId(agent.getId());
        log.setAgentSn(agent.getAgentSn());
        log.setAgentName(agent.getAgentName());
        log.setAgentLevel(agent.getAgentLevel());
        log.setMobile(agent.getMobile());
        log.setWechatNum(agent.getWechatNum());
        log.setOperatorId(auth.getUid());
        log.setOperatorName(auth.getRealName());
        log.setAmount(agentRenew.getAmount());
        if (CollUtil.isEmpty(list)) {
            log.setLogType(AgentLogTypeEnum.ZHSK.getValue());
        } else {
            log.setLogType(AgentLogTypeEnum.ZSXF.getValue());
        }
        log.setCustomerId(auth.getUid());
        log.setCustomerName(auth.getRealName());
        agentLogService.save(log);
    }

    @Override
    public IPage<AgentRenewVo> agentRenewList(Page page, Long agentId) {
        return baseMapper.agentRenewList(page, agentId);
    }

    @Override
    public List<AgencyFeeVo> selectAgencyFeeList(AgencyFeeQuery agentRenewQuery) {
        return baseMapper.selectAgencyFeeList(agentRenewQuery);
    }

    /**
     * 查询代理缴费列表
     *
     * @param page    分页
     * @param query   查询条件
     * @return  缴费记录
     */
    @Override
    public IPage<AgencyFeeVo> selectRenewList(Page page, AgencyFeeQuery query) {
        if (null != query.getAgentId()){
            Agent agent = agentService.getById(query.getAgentId());
            query.setAgentLevel(agent.getAgentLevel());
        }
        return baseMapper.selectRenewList(page, query);
    }

    /**
     * 查询代理缴费记录
     *
     * @param page    分页
     * @param query 查询条件
     * @return 缴费记录
     */
    @Override
    public IPage<AgentRenewVo> selectRenewRecordList(Page page, AgencyRecordQuery query) {
        if (null != query.getAgentId()){
            Agent agent = agentService.getById(query.getAgentId());
            query.setAgentLevel(agent.getAgentLevel());
        }
        Date now = new Date();
        List<AgentRenewVo> records = baseMapper.selectRenewRecordList(page, query);
        page.setRecords(records);
//        List<AgentRenewVo> records = agentRenewVoIPage.getRecords();
        if (CollUtil.isNotEmpty(records)){
                for(AgentRenewVo vo : records){
                    vo.setMobile(CommUtil.coverMobile(vo.getMobile()));
                    vo.setIdCard(CommUtil.coverIdcard(vo.getIdCard()));
                    vo.setIsExpire(DateUtil.compare(now,vo.getMaturityTime()) > 0 ? 1 : 0);
                }
        }
        return page;
    }
    /**
     * 统计代理缴费记录
     *
     * @param query 查询条件
     * @return 统计详情
     */
    @Override
    public RenewStats renewStats(AgencyRecordQuery query) {
        return baseMapper.renewStats(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editRecord(AgentRenewEditDto dto) {
        AgentRenew agentRenew = getById(dto.getId());
        agentRenew.setAmount(dto.getAmount());
        agentRenew.setUpdator(AuthUtil.getSysExt().getRealName());
        DateTime effEnd = DateUtil.parse(dto.getEffectEnd(), DatePattern.NORM_DATETIME_PATTERN);
        agentRenew.setEffectEnd(effEnd);
        updateById(agentRenew);
        Agent agent = agentService.getById(agentRenew.getAgentId());
        // 更改代理商表到期时间
        agent.setLastMaturityTime(agent.getMaturityTime());
        agent.setMaturityTime(effEnd);

//        createLog(auth, agentRenew, agent, list);

        agent.setIsEnable(WhetherEnum.YES.getValue());
        agent.setIsOfficial(WhetherEnum.YES.getValue());
        agentService.updateById(agent);
    }

}
